package org.bonorsoft.modules.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.aspect.annotation.PermissionData;
import org.bonorsoft.common.constant.UserConstants;
import org.bonorsoft.common.system.base.controller.BonorController;
import org.bonorsoft.common.system.query.QueryGenerator;
import org.bonorsoft.common.util.DateUtils;
import org.bonorsoft.modules.mobile.entity.MobileUser;
import org.bonorsoft.modules.mobile.service.IMobileUserService;
import org.bonorsoft.modules.mobileutils.redisutil.MobileRedisOperate;
import org.bonorsoft.modules.user.entity.MobileRole;
import org.bonorsoft.modules.user.service.IMobileRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

@Slf4j
@Controller
@RequestMapping("/mobile/role")
public class MobileRoleController extends BonorController<MobileRole, IMobileRoleService> {
    private String prefix = "system/role";

    @Autowired
    private IMobileRoleService mobileRoleService;

    @Autowired
    private IMobileUserService mobileUserService;

    /**
     * 首页
     */
    @RequiresPermissions("mobile:role:view")
    @GetMapping()
    public String index() {
        return prefix + "/role";
    }

    /**
     * 分页列表查询
     *
     * @param mobileRole
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "角色-分页列表查询")
    @RequiresPermissions("mobile:role:list")
    @GetMapping(value = "/list")
    @ResponseBody
    public Result<?> queryPageList(MobileRole mobileRole,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<MobileRole> queryWrapper = QueryGenerator.initQueryWrapper(mobileRole, req.getParameterMap());
        Page<MobileRole> page = new Page<MobileRole>(pageNo, pageSize);
        queryWrapper.eq("del_flag", 0);
        IPage<MobileRole> pageList = mobileRoleService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param mobileRole
     * @return
     */
    @AutoLog(value = "角色-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MobileRole mobileRole) {
        mobileRoleService.save(mobileRole);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap map) {
        map.put("role", mobileRoleService.getById(id));
        return prefix + "/edit";
    }

    /**
     * 编辑
     *
     * @param mobileRole
     * @return
     */
    @AutoLog(value = "角色-编辑")
    @RequiresPermissions("mobile:role:edit")
    @PostMapping(value = "/edit")
    @ResponseBody
    public Result<?> edit(@Validated MobileRole mobileRole, HttpServletRequest req) {
        //sysRoleService.checkRoleAllowed(sysRole);
        if (UserConstants.ROLE_NAME_KEY_NOT_UNIQUE.equals(mobileRoleService.checkRoleUnique("name", mobileRole, mobileRole.getName()))) {
            return Result.error("修改角色'" + mobileRole.getName() + "'失败，角色名称已存在");
        } else if (UserConstants.ROLE_NAME_KEY_NOT_UNIQUE.equals(mobileRoleService.checkRoleUnique("role_key", mobileRole, mobileRole.getRoleKey()))) {
            return Result.error("修改角色'" + mobileRole.getName() + "'失败，角色权限已存在");
        }
        mobileRole.setUpdateBy(getLoginUserName());
        mobileRole.setUpdateTime(DateUtils.getDate());
        //删除该角色下的所有用户的权限缓存
        MobileRedisOperate.delUserShiroByRoleId(mobileRole.getId());
        mobileRoleService.updateRole(mobileRole, req);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "角色-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        mobileRoleService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "角色-批量删除")
    @RequiresPermissions("mobile:role:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    @ResponseBody
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        try {
            this.mobileRoleService.removeByIds(Arrays.asList(ids.split(",")));
            return Result.ok("批量删除成功！");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "角色-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MobileRole sysRole = mobileRoleService.getById(id);
        return Result.ok(sysRole);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mobileRole
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MobileRole mobileRole) {
        return super.exportXls(request, mobileRole, MobileRole.class, "角色");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MobileRole.class);
    }

    /**
     * 角色状态修改
     */
    @AutoLog(value = "角色管理-角色状态修改", operateType = 3)
    @RequiresPermissions("mobile:role:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public Result<?> changeStatus(MobileRole role) {
        try {
            mobileRoleService.checkRoleAllowed(role);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        mobileRoleService.updateById(role);
        return Result.ok("修改成功！");
    }

    /**
     * 校验角色名称
     */
    @PostMapping("/checkRoleNameUnique")
    @ResponseBody
    public String checkRoleNameUnique(MobileRole role) {
        return mobileRoleService.checkRoleUnique("name", role, role.getName());
    }

    /**
     * 校验角色权限
     */
    @PostMapping("/checkRoleKeyUnique")
    @ResponseBody
    public String checkRoleKeyUnique(MobileRole role) {
        return mobileRoleService.checkRoleUnique("role_key", role, role.getRoleKey());
    }

    /**
     * 查看用户
     */
    @RequiresPermissions("mobile:role:edit")
    @GetMapping("/authUser/{roleId}")
    public String authUser(@PathVariable("roleId") Integer roleId, ModelMap mmap) {
        mmap.put("role", mobileRoleService.selectRoleById(roleId));
        return prefix + "/authUser";
    }

    /**
     * 查询已分配用户角色列表
     */
    @RequiresPermissions("mobile:role:list")
    @RequestMapping(value = "/authUser/allocatedList", method = RequestMethod.GET)
    @ResponseBody
    @PermissionData(value = "more", deptAlias = "d", userAlias = "u")
    public Result<?> allocatedList(MobileUser user,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Page<MobileUser> page = new Page<>(pageNo, pageSize);
        IPage<MobileUser> pageList = mobileUserService.pageByConditions(page, user, req);
        return Result.ok(pageList);
    }

    /**
     * 角色分配数据权限
     */
    @GetMapping("/authDataScope/{roleId}")
    public String authDataScope(@PathVariable("roleId") Integer roleId, ModelMap mmap) {
        mmap.put("role", mobileRoleService.selectRoleById(roleId));
        return prefix + "/dataScope";
    }

    /**
     * 保存角色分配数据权限
     */
    @RequiresPermissions("system:role:edit")
    @AutoLog(value = "角色管理-分配数据权限", operateType = 2)
    @PostMapping("/authDataScope")
    @ResponseBody
    public Result<?> authDataScopeSave(MobileRole role, HttpServletRequest req) {
        mobileRoleService.checkRoleAllowed(role);
        role.setUpdateBy(getLoginUserName());
        if (mobileRoleService.authDataScope(role, req) > 0) {
            return Result.ok("分配成功");
        }
        return Result.error("分配失败");
    }

}
